import { SubmitRecord } from '@/pages/OnlineJudge/DoQuestion/components/SubmitRecord';
import { getItemDefineById } from '@/services/ant-design-pro/dictionaryController';
import { doQuestionSubmit, getQuestionById } from '@/services/ant-design-pro/questionController';
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import gfm from '@bytemd/plugin-gfm';
import { Viewer } from '@bytemd/react';
import { useParams } from '@umijs/max';
import { Button, Col, Input, message, Row, Select, Space, Tag } from 'antd';
import { useEffect, useState } from 'react';
import MonacoEditor from 'react-monaco-editor';
import {randomFamousQuotes} from "@/services/ant-design-pro/questionSubmitController";
import {monacoThemeOption} from "@/common/monaco";

enum QuestionLevelEnum {
  SIMPLE = 0,
  MEDIUM = 1,
  HARD = 2,
}

const plugins = [
  gfm(),
  // Add more plugins here
];
export default () => {
  const editorDidMount = (editor, monaco) => {
    console.log('editorDidMount', editor);
    editor.focus();
  };

  const locationParam = useParams();

  const [languageOption, setLanguageOption] = useState<any[]>();
  const [questionSubmitRequest, setQuestionSubmitRequest] = useState<API.QuestionSubmitRequest>({
    questionId: locationParam?.id,
    language: 'JAVA',
    code: '',
  });
  const options = {
    selectOnLineNumbers: true,
  };

  const [questionSubmitEntity, setQuestionSubmit] = useState<API.QuestionSubmitEntity>();
  const onQuestionSubmit = async () => {
    const res = await doQuestionSubmit(questionSubmitRequest);
    if (res?.code === 200) {
      setQuestionSubmit({
        ...res?.data,
      });
      return;
    }
    message.error(res?.message);
  };

  /**
   * 获取代码语言选项
   */
  const getLanguageOption = () => {
    getItemDefineById({
      id: 'question-submit-language-enum',
    }).then((res) => {
      if (res?.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: item?.text,
              value: item?.value,
            };
          }) || [];
        setLanguageOption(data);
      }
    });
  };

  const [theme, setTheme] = useState<string>();

  /**
   * 获取当前题目
   */
  const [questionEntity, setQuestionEntity] = useState<API.QuestionEntity>();
  const getCurrentQuestionById = () => {
    getQuestionById({
      questionId: locationParam?.id || '',
    }).then((res) => {
      if (res?.code === 200) {
        setQuestionSubmitRequest({
          ...questionSubmitRequest,
          code: res?.data?.sampleCode,
        });
        setQuestionEntity({
          ...res?.data,
        });
        return;
      }
      message.error(res?.message);
    });
  };
  const [famousQuote,setFamousQuote] = useState("")
  const getRandomFamousQuote = async () => {
    const res = await randomFamousQuotes()
    if (res?.code === 200){
      setFamousQuote(res?.data || '')
      return;
    }
    message.error(res?.message)
  }

  useEffect(() => {
    getLanguageOption();
    getCurrentQuestionById();
    getRandomFamousQuote()
  }, []);

  return (
    <>
      <Row>
        <Col span={11}>
          <div>
            <ProCard
              boxShadow={true}
              tabs={{
                type: 'card',
              }}
              actions={[
                <SettingOutlined key="setting" />,
                <EditOutlined key="edit" />,
                <EllipsisOutlined key="ellipsis" />,
              ]}
            >
              <ProCard.TabPane key="description" tab="题目描述">
                {JSON.parse(questionEntity?.tags || '[]').map((tag: string) => {
                  return (
                    <Tag key={Date.now()} color="green">
                      {tag}
                    </Tag>
                  );
                })}
                <Space>
                  <span>时间限制(ms):{JSON.parse(questionEntity?.judgeConfig || '{}').timeLimit}</span>
                  <span>
                    内存限制(kb):{JSON.parse(questionEntity?.judgeConfig || '{}').memoryLimit}
                  </span>
                  <span>
                    {questionEntity?.level === QuestionLevelEnum.SIMPLE ? (
                      <Tag key={Date.now()} color="success">
                        简单
                      </Tag>
                    ) : questionEntity?.level === QuestionLevelEnum.MEDIUM ? (
                      <Tag key={Date.now()} color="green">
                        中等
                      </Tag>
                    ) : (
                      <Tag key={Date.now()} color="error">
                        困难
                      </Tag>
                    )}
                  </span>
                </Space>

                <Viewer value={questionEntity?.content} plugins={plugins} />
              </ProCard.TabPane>
              <ProCard.TabPane key="answer" tab="题目题解">
                题目题解
              </ProCard.TabPane>
              <ProCard.TabPane key="record" tab="提交记录">
                <SubmitRecord questionId={questionSubmitRequest?.questionId} />
              </ProCard.TabPane>
            </ProCard>
          </div>
        </Col>
        <Col span={1}></Col>

        <Col span={12}>
          <Space direction="vertical" size="small" style={{ display: 'flex' }}>
            <ProCard
              title={famousQuote}
              boxShadow={true}
              actions={[
                <Button key="1" type="link"></Button>,
                <Button key="1" type="link"></Button>,
                <Button key="1" type="link"></Button>,
                <Button key="1" type="link"></Button>,
                <Button key="1" type="link"></Button>,
                <Button key="1" type="link"></Button>,
                <Button key="running" type="default">
                  运行
                </Button>,
                <Button key="sumbit" type="primary" onClick={onQuestionSubmit}>
                  提交
                </Button>,
              ]}
              extra={
                <>
                  <Space>
                    <Space>
                      主题:
                      <Select
                        defaultValue="light"
                        style={{ width: 100 }}
                        options={monacoThemeOption}
                        onChange={(value) => setTheme(value)}
                      />
                    </Space>
                    <Space>
                      语言:
                      <Select
                        style={{ width: 100 }}
                        defaultValue={questionSubmitRequest?.language}
                        onChange={(value) =>
                          setQuestionSubmitRequest({
                            ...questionSubmitRequest,
                            language: value,
                          })
                        }
                        options={languageOption}
                      />
                    </Space>
                  </Space>
                </>
              }
            >
              <MonacoEditor
                // width="750"
                height="270"
                language="java"
                theme={theme}
                // theme="vs"
                value={questionSubmitRequest?.code}
                options={options}
                onChange={(code) =>
                  setQuestionSubmitRequest({
                    ...questionSubmitRequest,
                    code,
                  })
                }
                editorDidMount={editorDidMount}
              />
            </ProCard>
            <ProCard
              boxShadow={true}
              tabs={{
                type: 'card',
              }}
            >
              <ProCard.TabPane key="test" tab="测试用例">
                {questionEntity?.judgeCase}
                <Input width={20} value={questionEntity?.judgeCase?.inputs}></Input>
                <Input width={100} value={questionEntity?.judgeCase?.outputs}></Input>
              </ProCard.TabPane>
              <ProCard.TabPane key="testAnswer" tab="测试结果">
                {questionSubmitEntity?.message}
              </ProCard.TabPane>
            </ProCard>
          </Space>
        </Col>
      </Row>
    </>
  );
};
